from app.tools_jumpserver.models.jumpserver_audit import JumpserverAudit
from app.tools_jumpserver.handlers import JumpserverClient
from common.database import SessionLocal
from core.celery import celery_app
from core.logger import logger


@celery_app.task(bind=True)
def jumpserver_audit_export_data_async(self):
    session = SessionLocal()
    client = JumpserverClient()
    for item in client.get_users_list():
        if uuid := item.get("id", None):
            if perm_assets := client.get_user_assets_by_uuid(uuid):
                for perm_asset in perm_assets:
                    JumpserverAudit.save(session, {"username": item.get("username"), "hostname": perm_asset.get("hostname"),
                                                   "ip": perm_asset.get("ip"),
                                                   "system_user": perm_asset.get("system_users_granted")[0].get("username")})
    logger.info('jumpserver 审计上报数据完成')
    session.close()


if __name__ == '__main__':
    jumpserver_audit_export_data_async()
